#!/bin/sh /etc/rc.common
# relayway-cored — OpenWrt procd service for the embedded router admin API +
# dashboard. Serves the Flutter web UI (shipped at /usr/share/relayway-cored/www)
# on the UCI-configured port (default 7654) so the luci-app can iframe it.
#
# UCI: config relayway 'cored'  →  option port '7654'  option listen '0.0.0.0'
#   listen defaults to 0.0.0.0 so the panel is reachable from a LAN computer's
#   browser out of the box (OpenWrt's firewall DROPs WAN→router input, so this is
#   LAN-only in practice). NOTE: /consumer login is token-gated, but /api/v1
#   admin endpoints are only HMAC-gated when RELAYWAY_CORED_HMAC_SECRET is set
#   (this init does not set one), so on the LAN they are currently unauthenticated.
#   Set listen '127.0.0.1' for loopback-only (then reach it via SSH tunnel).
START=96
STOP=09
USE_PROCD=1
PROG=/usr/bin/relayway-cored
EXTRA_COMMANDS="reset_password"
EXTRA_HELP="        reset_password  Reset the local Web-panel password (root console/SSH only)"

reset_password() {
    [ "$(id -u 2>/dev/null)" = "0" ] || {
        echo "relayway-cored: reset_password requires root." >&2
        return 1
    }
    [ -r /dev/tty ] && [ -w /dev/tty ] || {
        echo "relayway-cored: reset_password requires an interactive SSH or console terminal." >&2
        return 1
    }

    # Never leak the password when an operator invoked the init script through
    # `sh -x`. The value is passed to cored only over stdin, never argv/env/a
    # temporary file.
    case "$-" in *x*) set +x ;; esac
    _relayway_reset_echo_disabled=0
    _relayway_reset_was_running=0
    _relayway_reset_service_stopped=0
    _relayway_reset_cleanup() {
        if [ "$_relayway_reset_echo_disabled" = "1" ]; then
            stty echo </dev/tty 2>/dev/null || true
            _relayway_reset_echo_disabled=0
            printf '\n' >/dev/tty
        fi
        unset _relayway_reset_password _relayway_reset_confirmation
        if [ "$_relayway_reset_service_stopped" = "1" ] && \
           [ "$_relayway_reset_was_running" = "1" ]; then
            start >/dev/null 2>&1 || true
            _relayway_reset_service_stopped=0
        fi
    }
    trap '_relayway_reset_cleanup' EXIT
    trap '_relayway_reset_cleanup; trap - EXIT; exit 130' HUP INT TERM

    printf 'New local panel password: ' >/dev/tty
    stty -echo </dev/tty || return 1
    _relayway_reset_echo_disabled=1
    IFS= read -r _relayway_reset_password </dev/tty || return 1
    printf '\nConfirm local panel password: ' >/dev/tty
    IFS= read -r _relayway_reset_confirmation </dev/tty || return 1
    stty echo </dev/tty || return 1
    _relayway_reset_echo_disabled=0
    printf '\n' >/dev/tty

    [ -n "$_relayway_reset_password" ] || {
        echo "relayway-cored: password must not be empty." >&2
        return 1
    }
    [ "$_relayway_reset_password" = "$_relayway_reset_confirmation" ] || {
        echo "relayway-cored: password confirmation does not match." >&2
        return 1
    }
    _relayway_reset_bytes="$(printf '%s' "$_relayway_reset_password" | wc -c | tr -d ' ')"
    case "$_relayway_reset_bytes" in
        ''|*[!0-9]*)
            echo "relayway-cored: could not validate password length." >&2
            return 1
            ;;
    esac
    [ "$_relayway_reset_bytes" -le 256 ] || {
        echo "relayway-cored: password exceeds 256 UTF-8 bytes." >&2
        return 1
    }
    [ "$_relayway_reset_bytes" -ge 6 ] || {
        echo "relayway-cored: password is too short (minimum 6 characters)." >&2
        return 1
    }

    if running >/dev/null 2>&1; then
        _relayway_reset_was_running=1
        if ! stop; then
            if ! pidof relayway-cored >/dev/null 2>&1; then
                _relayway_reset_service_stopped=1
            fi
            echo "relayway-cored: could not stop the running service; password was not changed." >&2
            return 1
        fi
        _relayway_reset_service_stopped=1
    fi

    _relayway_reset_wait=0
    while pidof relayway-cored >/dev/null 2>&1; do
        _relayway_reset_wait=$((_relayway_reset_wait + 1))
        [ "$_relayway_reset_wait" -lt 15 ] || {
            echo "relayway-cored: a daemon still owns the state; password was not changed." >&2
            return 1
        }
        sleep 1
    done

    if ! printf '%s\n%s\n' \
        "$_relayway_reset_password" \
        "$_relayway_reset_confirmation" \
        | "$PROG" --reset-admin-password-from-stdin-and-exit; then
        echo "relayway-cored: password reset did not complete cleanly; after service recovery, try the new password and rerun this command if needed." >&2
        return 1
    fi

    if [ "$_relayway_reset_was_running" = "1" ] && ! start; then
        # Do not let the EXIT recovery path mask a deterministic restart
        # failure after the password was already committed.
        _relayway_reset_service_stopped=0
        _relayway_reset_cleanup
        trap - EXIT HUP INT TERM
        echo "relayway-cored: password changed, but the service did not restart; run '$0 start'." >&2
        return 1
    fi
    _relayway_reset_service_stopped=0
    _relayway_reset_cleanup
    trap - EXIT HUP INT TERM
    echo "relayway-cored: local panel password changed. Existing browser sessions were invalidated."
}

prepare_tun_device() {
    # Loading is local/idempotent and must never depend on network access at
    # boot. If the kernel registered the misc device but devtmpfs/hotplug did
    # not create its node, reconstruct it from the authoritative sysfs major
    # and minor. Never mknod when the driver itself is absent: an empty 10:200
    # node would only turn a clear install error into a misleading open error.
    command -v modprobe >/dev/null 2>&1 && modprobe tun >/dev/null 2>&1 || true
    [ -r /sys/class/misc/tun/dev ] || return 1

    local dev major minor expected_hex actual_hex actual_dec
    dev="$(cat /sys/class/misc/tun/dev 2>/dev/null)"
    major="${dev%%:*}"
    minor="${dev#*:}"
    case "$major:$minor" in
        *[!0-9:]*|:|:*|*:) return 1 ;;
    esac

    # A character node alone is not proof that the driver is registered; stale
    # /dev state must not enable routes or the IPv6 guard. A wrong device number
    # is equally unusable, so replace it from the authoritative sysfs value.
    expected_hex="$(printf '%x:%x' "$major" "$minor" 2>/dev/null)"
    actual_hex="$(stat -c '%t:%T' /dev/net/tun 2>/dev/null || true)"
    actual_dec="$(ls -ln /dev/net/tun 2>/dev/null | awk '{gsub(",", "", $5); print $5 ":" $6; exit}')"
    if [ -c /dev/net/tun ] \
        && { [ "$actual_hex" = "$expected_hex" ] || [ "$actual_dec" = "$major:$minor" ]; }; then
        return 0
    fi
    [ ! -e /dev/net/tun ] || rm -f /dev/net/tun 2>/dev/null || return 1
    mkdir -p /dev/net || return 1
    mknod /dev/net/tun c "$major" "$minor" 2>/dev/null || return 1
    chmod 0600 /dev/net/tun 2>/dev/null || true
    [ -c /dev/net/tun ]
}

# cored versions before the exact-resolver snapshot fix restored OpenWrt's
# generated /tmp/resolv.conf as only `nameserver 127.0.0.1`, dropping its
# search domain and IPv6 loopback entry. During an upgrade the old process can
# perform that lossy teardown immediately before the new one starts. Repair
# only that exact legacy signature; every other resolver is operator/network
# state and must remain untouched.
repair_legacy_openwrt_resolver() {
    [ -L /etc/resolv.conf ] || return 0
    [ "$(readlink /etc/resolv.conf 2>/dev/null)" = "/tmp/resolv.conf" ] || return 0
    [ "$(wc -l < /tmp/resolv.conf 2>/dev/null | tr -d ' ')" = "1" ] || return 0
    grep -qx 'nameserver 127.0.0.1' /tmp/resolv.conf 2>/dev/null || return 0
    [ -x /etc/init.d/dnsmasq ] || return 0

    /etc/init.d/dnsmasq restart >/dev/null 2>&1 || {
        logger -t relayway-cored \
            "legacy resolver signature detected but dnsmasq regeneration failed" 2>/dev/null || true
        return 1
    }
}

# rc.common invokes this after procd has synchronously stopped the prior
# generation. Restrict the migration to restart/reload so an ordinary stop or
# router shutdown never starts dnsmasq again.
service_stopped() {
    case "${action:-}" in
        restart|reload) repair_legacy_openwrt_resolver ;;
    esac
}

start_service() {
    config_load relayway
    local port listen airport_id middleware_url middleware_urls base_url hmac_secret allowed_hosts api_transport_bundle_file config dat_dir tun tun_instances capture_mode tcp_lane memory_tier lean_rcvbuf_governor memory_pressure log_level
    config_get port   cored port   7654
    config_get listen cored listen '0.0.0.0'
    # Per-airport identity (baked by build-ipk.sh, or set by an operator). cored's
    # consumer channel reads RELAYWAY_CORED_AIRPORT_ID / RELAYWAY_CORED_MW_URL to
    # auto-register with the right airport/brand. Unset → consumer channel stays
    # idle (the dashboard still serves; operator can configure later via UCI).
    config_get airport_id     cored airport_id     ''
    config_get middleware_url cored middleware_url ''
    # Ordered failover list (comma/whitespace separated, domestic-first); cored's
    # mw_upstream::candidates() fails over across these on transport errors so a
    # GFW-RST'd / down overseas ingress no longer wedges login. Empty → only the
    # single middleware_url is used (no failover).
    config_get middleware_urls cored middleware_urls ''
    # Airport-managed artifact and geo-data mirror.
    config_get base_url       cored base_url       ''
    config_get hmac_secret    cored hmac_secret    ''
    config_get api_transport_bundle_file cored api_transport_bundle_file ''
    # Extra Host/Origin names accepted by cored's anti-CSRF / anti-DNS-rebinding
    # gate. Out of the box the gate already accepts IP literals, `localhost`,
    # bare hostnames and the local-only suffixes (.lan/.local/.home.arpa/
    # .internal/.localdomain/.home), which covers every normal LAN access path.
    # A DELEGATED domain (reverse proxy / DDNS) must be opted in here, otherwise
    # its API calls answer 403 while the static panel still loads.
    #   uci set relayway.cored.allowed_hosts='router.example.com'
    #   uci commit relayway && /etc/init.d/relayway-cored restart
    config_get allowed_hosts  cored allowed_hosts  ''
    # Engine config + TUN data plane (web softrouter gap §6). WITHOUT -c, cored
    # runs an EMPTY engine (HTTP-only) so `consumer_connect` injects a node that
    # nothing feeds → "connected but no traffic". WITH --tun, cored brings up the
    # transparent TUN data plane that routes LAN traffic through the selected
    # node. dat_dir holds rd.bin/rs.bin so geoip:/geosite: CN-split rules work.
    config_get config   cored config  '/etc/relayway/config.json'
    config_get dat_dir  cored dat_dir '/etc/relayway'
    config_get_bool tun cored tun 1
    config_get tun_instances cored tun_instances ''

    # The init layer only validates the kernel/device prerequisite.  Guard
    # restore/apply is intentionally owned only by the cored process after it
    # has acquired the cross-process OpenWrt policy lock.  An init-level restore
    # could otherwise dismantle a concurrently running daemon's data plane.
    if [ "$tun" = "1" ] && ! prepare_tun_device; then
        logger -t relayway-cored \
            "TUN kernel driver unavailable; starting control plane only (connect returns 503)" 2>/dev/null || true
    fi

    # NOTE (web softrouter gap §6 Part 2): crash recovery is handled IN cored
    # (src/tun_recovery.rs), not here. On a hard crash (SIGKILL/OOM) cored's
    # in-process teardown can't run, so on the next start cored restores the WAN
    # default route + resolv.conf from a persisted gateway marker. An earlier
    # init-level `/etc/init.d/network reload` attempt was dropped — verified on
    # OpenWrt 25.12.4 that it does NOT re-assert the default route.

    procd_open_instance
    # Keep a tiny parent process around the data-plane daemon so hard exits can
    # be attributed on the next startup. It forwards TERM/INT to the child and
    # records exact exit code/signal plus bounded OOM/watchdog kernel evidence;
    # procd still owns respawn policy for the parent.
    procd_set_param command "$PROG" --supervise --listen "${listen}:${port}"
    [ -f "$config" ]  && procd_append_param command -c "$config"
    [ "$tun" = "1" ]  && procd_append_param command --tun
    [ -n "$dat_dir" ] && procd_append_param command -d "$dat_dir"
    # cored serves the dashboard from $RELAYWAY_CORED_WWW (default
    # /usr/share/relayway-cored/www) — set explicitly so it survives a
    # future default change.
    procd_set_param env RELAYWAY_CORED_WWW=/usr/share/relayway-cored/www
    procd_append_param env RELAYWAY_CORED_PLATFORM=openwrt
    [ -n "$airport_id" ]     && procd_append_param env "RELAYWAY_CORED_AIRPORT_ID=$airport_id"
    [ -n "$middleware_url" ] && procd_append_param env "RELAYWAY_CORED_MW_URL=$middleware_url"
    [ -n "$middleware_urls" ] && procd_append_param env "RELAYWAY_CORED_MW_URLS=$middleware_urls"
    [ -n "$base_url" ]       && procd_append_param env "RELAYWAY_CORED_BASE_URL=$base_url"
    [ -n "$hmac_secret" ]    && procd_append_param env "RELAYWAY_CORED_HMAC_SECRET=$hmac_secret"
    [ -n "$api_transport_bundle_file" ] && procd_append_param env "RELAYWAY_CORED_API_TRANSPORT_BUNDLE_FILE=$api_transport_bundle_file"
    [ -n "$allowed_hosts" ]  && procd_append_param env "RELAYWAY_CORED_ALLOWED_HOSTS=$allowed_hosts"
    # Point cored's geo-DB auto-download at the airport's mirror (base_url, which
    # is CN-reachable) instead of the GitHub default. cored runtime-downloads
    # rd.bin/rs.bin when they're missing/stale; the GitHub default fails on a CN
    # router with no node connected → empty geoip:/geosite: matchers → CN-direct
    # breaks. build-release-bundle.sh publishes rd.bin/rs.bin next to install.sh
    # on base_url. (install.sh/the .ipk already lay the files down; this is the
    # self-heal path if they're ever missing.)
    [ -n "$base_url" ]       && procd_append_param env "RELAYWAY_GEOIP_URL=$base_url/rd.bin"
    [ -n "$base_url" ]       && procd_append_param env "RELAYWAY_GEOSITE_URL=$base_url/rs.bin"
    [ -n "$tun_instances" ]  && procd_append_param env "RELAYWAY_TUN_INSTANCES=$tun_instances"
    # raw-IP capture mode. DEFAULT is now 'all' (unset → native.rs AllForwarded):
    # ALL forwarded LAN traffic enters the user-space TUN; cored still splits
    # geoip:cn/private + geosite:cn to the `direct` outbound. This fixes apps that
    # dial HARDCODED IPs WITHOUT a DNS lookup — Telegram MTProto, some games, VoIP
    # — which never get a fake-IP, so under the old 'fakeip' default they missed
    # the `to 198.18.0.0/15` policy rule, fell to the WAN default, and got blocked
    # (2026-06-21 prod incident). ESCAPE HATCH: set UCI relayway.cored.capture_mode=
    # 'fakeip' to RESTORE the old kernel-fast-path (only fake-IP dests enter the
    # TUN; real-IP/direct bypass the user-space stack) — recommended for weak-CPU
    # routers where 'all' throttles big direct downloads, at the cost of re-exposing
    # raw-IP apps to blocking. See relayway-proxy native.rs linux_tun_capture_mode.
    config_get capture_mode cored capture_mode ''
    [ -n "$capture_mode" ] && procd_append_param env "RELAYWAY_TUN_CAPTURE_MODE=$capture_mode"
    # TCP lane. Unset (default since 2.36.0): cored moves LAN TCP off the
    # user-space TUN onto a kernel-TCP listener fed by fw4 dstnat redirect
    # rules (comment relayway-cored-redirect) when the router has fw4 and the
    # kernel supports nft redirect + SO_ORIGINAL_DST; otherwise TCP stays on
    # the TUN with one INFO log line. DNS and all UDP stay on the TUN.
    # 'tun' (or off/0/false) keeps all TCP on the TUN; 'redirect' asks for the
    # lane explicitly (WARN on a router that cannot do it). /api/v1/status
    # .tcp_lane shows the lane and whether it is the default or explicit.
    #   uci set relayway.cored.tcp_lane='tun'
    config_get tcp_lane cored tcp_lane ''
    [ -n "$tcp_lane" ] && procd_append_param env "RELAYWAY_CORED_TCP_LANE=$tcp_lane"
    # Memory tier. Unset → cored decides from MemTotal (≤ 640 MiB ⇒ constrained:
    # one TUN table, 64 KiB windows, lean LAN flows, Phantom pool 1 per lane).
    # 'normal' / 'constrained' force either; any other value is ignored by cored.
    #   uci set relayway.cored.memory_tier='normal'
    # 'off' disables the constrained tier's upstream receive-buffer governor
    # (SO_RCVBUFFORCE + TCP_WINDOW_CLAMP on lean LAN flows).
    #   uci set relayway.cored.lean_rcvbuf_governor='off'
    # Both are read once at start: uci commit relayway && restart this service.
    config_get memory_tier cored memory_tier ''
    [ -n "$memory_tier" ] && procd_append_param env "RELAYWAY_MEMORY_TIER=$memory_tier"
    config_get lean_rcvbuf_governor cored lean_rcvbuf_governor ''
    [ -n "$lean_rcvbuf_governor" ] && procd_append_param env "RELAYWAY_LEAN_RCVBUF_GOVERNOR=$lean_rcvbuf_governor"
    # Memory pressure monitor: auto (default), on (force pressure), or off.
    # The monitor reads RELAYWAY_MEMORY_PRESSURE once when the process starts.
    config_get memory_pressure cored memory_pressure ''
    [ -n "$memory_pressure" ] && procd_append_param env "RELAYWAY_MEMORY_PRESSURE=$memory_pressure"
    # Log level pinned to `info` for production: a soft-router has little storage
    # and (below) logs go to logd, so never let it accumulate verbose/sensitive
    # output. Operators can raise it transiently via UCI for debugging.
    config_get log_level cored log_level 'info'
    procd_append_param env "RELAYWAY_CORED_LOG=$log_level"
    # procd defaults to a 5s TERM grace period. cored's child performs a bounded
    # Flow-to-disk drain and verified TUN teardown, while the tracked supervisor
    # waits up to 45s before killing that child. Give the parent time to own the
    # whole shutdown so procd cannot SIGKILL it and leave an orphan child holding
    # the route lock or HTTP port. If the parent dies anyway (SIGKILL/OOM), the
    # kernel sends the child SIGTERM (PR_SET_PDEATHSIG), and the respawned child
    # stops an orphan that still holds the policy lock (SIGTERM, then SIGKILL
    # after 45s) before it takes over, so respawn and `restart` recover alone.
    procd_set_param term_timeout 60
    procd_set_param respawn 3600 5 5
    # stdout/stderr → procd → logd: a size-bounded syslog ring buffer in RAM
    # (auto-rotates, cleared on reboot), NOT a growing file on the router's
    # flash. `logread` shows recent lines; old ones drop off automatically — so
    # cored logs self-clean and never fill the limited storage.
    procd_set_param stdout 1
    procd_set_param stderr 1
    procd_close_instance
}

reload_service() {
    restart
}

service_triggers() {
    # LuCI Firewall -> Save & Apply rebuilds fw4 and removes RelayWay's
    # runtime-only rules. A firewall configuration event also restarts cored so
    # its normal activation path can reinstall them; the in-process watchdog
    # remains the safety net for direct flushes and any service-ordering race.
    procd_add_reload_trigger "firewall"
}
